override func viewDidLoad() {
super.viewDidLoad()
let imageAddress = "http://p9.pstatp.com/origin/2ed20004b67c9d120a4e"
//產生URLSession的實體
let session = URLSession(configuration: .default)
//產生URL
if let imageUrl = URL(string: imageAddress){
//呼叫downloadTask方法
let newTask = session.downloadTask(with: imageUrl, completionHandler: { (/*此url指的是下載下來的資料在手機上的url跟前面的url不一樣*/url:URL?, response:URLResponse?, error:Error?) in
//如果有錯誤
if error != nil{
print(error?.localizedDescription)
return
}else{
if let downloadUrl = url{
//用檔案在手機內的位置去產生一個Data
do{
let downloadData = try Data(contentsOf: downloadUrl)
let loadedImage = UIImage(data: downloadData)
DispatchQueue.main.async {
self.myImageView.image = loadedImage
}
}catch {
print(error.localizedDescription)
}
}
}
})
newTask.resume()
}
}
#import "檔案名稱"
let testReachability = Reachability(hostName: "www.google.com.tw")
if testReachability?.currentReachabilityStatus().rawValue == 0{
print("there is no internet")
}else{
print("The internet is fine")
}
PS: hostName指的是測試網頁,如果可以成功連上這個網站,就代表網路ok,才去執行後面的事情。